#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：tools
@File    ：config.py配置文件
@IDE     ：PyCharm
@Author  ：Kongbai
@Date    ：2021/9/24 10:41
'''
import json
import os
import random
import time
import tkinter as tk
import winreg
import markdown
import requests
from PIL import Image, ImageTk
from setting import access_token

app_name = "Bdown"  # 软件名称
version = "V2.5.0"  # 版本号
declaration="软件声明:\n本软件属于开源软件,禁止商业用途,发现请举报!\n一切因使用本软件而引致之任何意外、疏忽、诽谤、版权\n或知识产权侵犯及其所造成的损失(包括在非官方站点下载本软件而感染电脑病毒)，\n本软件概不负责，亦不承担任何法律责任!"

class Config:
    def __init__(self):
        self.window = tk.Tk()
        self.check_app_version()
        self.setting_base_config()
        self.setting_user_default_config()
        self.load_config()
        self.tk_init()
        self.setting_img()

    # 获取最新版本号
    def check_version(self):
        try:
            api = "https://gitee.com/api/v5/repos/Kongbaizdl/Bdown/releases"
            response = requests.get(url=api,
                                    params={"page": 1, "per_page": 50,
                                            "direction": 'desc',
                                            "access_token":access_token,
                                            })
            print(response.url)
        except:
            self.internet = False
            return False
        self.internet = True
        return response.json()

    def check_app_version(self):
        r = self.check_version()
        all_version = [i['tag_name'] for i in r]
        self.version_data = {
            "new_version": r[0]['tag_name'] if r else version,  # 请求出现问题,可能网络问题!使版本等于旧版本
            "app_name": app_name,
            "user_version": version,
            "user_app_is_valid": version in all_version,
            "new_url": "https://gitee.com/Kongbaizdl/Bdown/releases/",
            "version_desc": markdown.markdown(r[0]['body'])
        }

    def setting_base_config(self):
        # 不可变
        self.config_path = os.path.join(os.path.dirname(self.get_desktop()), ".BilibliDown")  # 配置文件存放的地方
        if not os.path.exists(self.config_path): os.mkdir(self.config_path)  # 创建配置文件目录
        self.user_file = os.path.join(self.config_path, "user_info.json")  # 存放配置文件的路径,不可改变
        self.bg_img = os.path.join(self.config_path, "bg_img")
        if not os.path.exists(self.bg_img): os.mkdir(self.bg_img)

    def setting_user_default_config(self):
        self.temp_dirname = os.path.join(self.config_path, "temp")  # 默认临时缓存音频文件目录
        self.result_dirname = self.get_desktop()  # 默认输出文件路径,桌面
        self.bg_img_list = ["https://gitee.com/Kongbaizdl/tuchuang/raw/master/img/bg/bg.png",
                            "https://cdn.pixabay.com/photo/2021/10/13/11/31/couple-6706278_960_720.jpg",
                            "http://img.netbian.com/file/2021/1029/77cdb4ee797bba3bd38ad26042d0c204.jpg",
                            "http://img.netbian.com/file/2021/0912/1597c35f145079bf0731e8ac09be4583.jpg",
                            "http://img.netbian.com/file/2021/0725/39b7280f0ba31a3a7ba3cec9413b4c2e.jpg",
                            "http://img.netbian.com/file/2021/0928/5718782225ac0c9269b7857d52d0f850.jpg",
                            "http://img.netbian.com/file/2021/0829/2a56e70351b67273bc5e8ac5a62b1784.jpg",
                            "http://img.netbian.com/file/2021/0726/7ea8ed7c9b17216c10c7e9d1ce2b047a.jpg",
                            "http://img.netbian.com/file/2021/0703/f27b49517d6436c5bdc301fd711631e4.jpg",
                            ]  # 网络背景图片路径
        self.down_threading_num = 14  # 下载线程数
        self.now_show_frame_index = 0  # 首次显示的页面
        self.cookie = ''  # 用户登陆cookie
        self.info=''
        self.init_config = {"cookie": self.cookie,"info":self.info,
                            "down_threading_num": self.down_threading_num, "bg_img_list": self.bg_img_list,
                            "result_dirname": self.result_dirname, "temp_dirname": self.temp_dirname,
                            "now_show_frame_index": self.now_show_frame_index
                            }

    def tk_init(self):
        self.title = f"{app_name}  {version} (By:Kongbai.Zdl)"  # 软件窗口标题
        self.win_width = 1500
        self.win_height = 864
        self.window.title(self.title)
        self.window.config(bg='white')
        self.window.geometry(f"{self.win_width}x{self.win_height}")  # 固定宽高
        self.window.resizable(0, 0)  # 窗口大小不可变

    def load_config(self):
        ###################加载配置文件############################
        # 配置文件不存在,创建初始化配置文件信息,存在,加载配置文件
        if not os.path.exists(self.user_file):
            # 初始化默认配置文件
            with open(self.user_file, 'w', encoding='utf8') as fp:
                self.config_data = self.init_config
                json.dump(self.config_data, fp)
        else:
            with open(self.user_file, 'r', encoding='utf8') as fp:
                self.config_data = json.load(fp)
            # 判断配置文件是否破坏
            if set(self.config_data.keys()) != set(self.init_config.keys()):
                # 初始化默认配置文件
                with open(self.user_file, 'w', encoding='utf8') as fp:
                    self.config_data = self.init_config
                    json.dump(self.config_data, fp)

        # 判断配置文件中的目录是否存在,不存在创建,防止用户修改路径
        if not os.path.exists(self.config_data['temp_dirname']): os.makedirs(self.config_data['temp_dirname'])
        if not os.path.exists(self.config_data['result_dirname']): os.makedirs(
            self.config_data['result_dirname'])

    def setting_img(self):
        # 从配置文件中选取图片链接生成tk_img对象
        self.tk_image = self.get_img(random.choice(self.config_data['bg_img_list']), resize=(1318, 811))  # 背景图
        window_icon_url = "https://gitee.com/Kongbaizdl/tuchuang/raw/master/img/bg/icon.ico"
        self.window_icon = self.get_img(window_icon_url, resize=(100, 100))
        self.window.iconphoto(False, self.window_icon[1])  # 窗口图

    # 获取系统桌面路径
    @staticmethod
    def get_desktop():
        key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
                             r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders')
        return winreg.QueryValueEx(key, "Desktop")[0]

    # 获取网络背景图片
    def get_img(self, url, resize):
        # 判断本地图片有没有缓存
        img_path = os.path.join(self.bg_img, url.split('/')[-1])
        if os.path.exists(img_path):
            image = Image.open(img_path)
            pil_image = image.resize(resize, Image.ANTIALIAS)
            tk_image = ImageTk.PhotoImage(pil_image)
            return True, tk_image
        else:
            try:
                # 下载图片数据
                image_bytes = requests.get(url).content
                with open(img_path, 'wb') as f:
                    f.write(image_bytes)
                # 将数据存放到data_stream中
                # data_stream = io.BytesIO(image_bytes)
                # 转换为图片格式
                pil_image = Image.open(img_path)

                pil_image = pil_image.resize(resize, Image.ANTIALIAS)  # resize image with high-quality
                # 将pil格式的图片转换为tk格式的image
                tk_image = ImageTk.PhotoImage(pil_image)
                return True, tk_image
            except:
                # 网络异常 生成纯色图片
                new_img = Image.new('RGB', resize, (153, 188, 206))  # 颜色模式,长宽,rgb里面的颜色
                tk_image = ImageTk.PhotoImage(new_img)
                return False, tk_image

if __name__ == '__main__':
    now_time = time.time()
    configer = Config()
    sub_time = time.time() - now_time  # 测试启动时间
    print(sub_time)
